import http.server
import socketserver
import threading
import requests
import time

# 创建一个自定义的请求处理类，继承自http.server.BaseHTTPRequestHandler
class RequestHandler(http.server.BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path == '/terminal':
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length).decode('utf-8')

            # 在这里处理接收到的数据
            received_text = post_data
            print(f"Received text: {received_text}")

            # 返回响应给客户端
            response_text = "Request received successfully"
            self.send_response(200)
            self.send_header('Content-Type', 'text/plain')
            self.send_header('Content-Length', len(response_text))
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(response_text.encode('utf-8'))
        elif self.path == '/update':
                        # 返回响应给客户端
            print("update")
            response_text = "Request received successfully"
            self.send_response(200)
            self.send_header('Content-Type', 'text/plain')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(response_text.encode('utf-8'))


    # def do_OPTIONS(self):
    #     # 处理OPTIONS请求，允许跨域请求
    #     self.send_response(200)
    #     self.send_header('Access-Control-Allow-Origin', '*')
    #     self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
    #     self.send_header('Access-Control-Allow-Headers', 'Content-Type')
    #     self.end_headers()

# 指定服务器监听的地址和端口
host = 'localhost'
port = 8080

def updater():
    i = 0
    url = 'http://localhost:8080/update'
    while True:
        i+=1
          # 替换为你的目标URL
        # 定义要发送的数据
        data = {'plain': f"Updating...{i}"}  # 替换为你要发送的数据
        # 发送POST请求
        response = requests.post(url, data=data)
        # 检查响应状态码
        if response.status_code == 200:
            print('POST请求成功')
            print('服务器响应:', response.text)
        else:
            print('POST请求失败')
        time.sleep(5)

# threading.Thread(target=updater, daemon=True).start()

# 创建HTTP服务器并指定请求处理类
with socketserver.TCPServer((host, port), RequestHandler) as server:
    print(f"Server listening on http://{host}:{port}")
    server.serve_forever()
    # 保持服务器运行